package com.centling.smartSealForPhone.widget.galleryview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.application.SmartSeal;
import java.util.ArrayList;
import java.util.List;

public class ScrollGalleryView
        extends LinearLayout {
    private Context context;
    private FragmentManager fragmentManager;
    private List<MediaInfo> mListOfMedia;

    private int thumbnailSize;
    private boolean zoomEnabled;

    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;
    private HorizontalScrollView horizontalScrollView;
    private LinearLayout thumbnailsContainer;

    public ScrollGalleryView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        mListOfMedia = new ArrayList<>();

        setOrientation(VERTICAL);
        LayoutInflater.from(context).inflate(R.layout.layout_scroll_gallery_view, this, true);

        horizontalScrollView = (HorizontalScrollView) findViewById(R.id.thumbnails_scroll_view);
        thumbnailsContainer = (LinearLayout) findViewById(R.id.thumbnails_container);
        thumbnailsContainer.setPadding(SmartSeal.screenWidth / 2, 0,
                SmartSeal.screenWidth / 2, 0);
    }

    public ScrollGalleryView setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
        initializeViewPager();
        return this;
    }

    private void initializeViewPager() {
        viewPager = (HackyViewPager) findViewById(R.id.vp_gallery);
        pagerAdapter = new ImageFragmentAdapter(fragmentManager, mListOfMedia, zoomEnabled);
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(viewPagerChangeListener);
    }

    public ScrollGalleryView addMedia(List<MediaInfo> infos) {
        if (infos == null) {
            throw new NullPointerException("Infos may not be null!");
        }

        for (int i = 0; i < infos.size(); i++) {
            MediaInfo info = infos.get(i);
            mListOfMedia.add(info);
            final ImageView thumbnail = addThumbnail(i + 1, infos.size(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.iv_default));
            info.getLoader().loadThumbnail(getContext(), thumbnail, new MediaLoader.SuccessCallback() {
                        @Override
                        public void onSuccess(Drawable drawable) {
                            thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        }
                    });
            pagerAdapter.notifyDataSetChanged();
//            viewPager.setOffscreenPageLimit(infos.size());
        }
        thumbnailsContainer.getChildAt(0).setSelected(true);
        return this;
    }

    public ScrollGalleryView setThumbnailSize(int thumbnailSize) {
        this.thumbnailSize = thumbnailSize;
        return this;
    }

    public ScrollGalleryView setZoom(boolean zoomEnabled) {
        this.zoomEnabled = zoomEnabled;
        return this;
    }

    private ImageView addThumbnail(int position, int size, Bitmap image) {
        LayoutParams lp = new LayoutParams(thumbnailSize, thumbnailSize);
        lp.setMargins(10, 10, 10, 10);
        Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, thumbnailSize, thumbnailSize);

        FrameLayout itemView = (FrameLayout) LayoutInflater.from(context).inflate(
                R.layout.layout_gallery_item, this, false);
        itemView.setLayoutParams(lp);
        ImageView thumbnailView = createThumbnailView(itemView.getChildAt(0), thumbnail);
        TextView tvTag = (TextView) itemView.findViewById(R.id.tv_gallery_position);
        tvTag.setText(position + " / " + size);
        thumbnailsContainer.addView(itemView);
        return thumbnailView;
    }

    private ImageView createThumbnailView(View view, Bitmap thumbnail) {
        ImageView thumbnailView = (ImageView) view;
        thumbnailView.setImageBitmap(thumbnail);
        thumbnailView.setTag(mListOfMedia.size() - 1);
        thumbnailView.setOnClickListener(thumbnailOnClickListener);
        thumbnailView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return thumbnailView;
    }

    public void addOnPageChangeListener(final ViewPager.OnPageChangeListener listener) {
        viewPager.clearOnPageChangeListeners();
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
                listener.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                scroll(thumbnailsContainer.getChildAt(position));
                for (int i = 0; i < thumbnailsContainer.getChildCount(); i++) {
                    thumbnailsContainer.getChildAt(i).setSelected(false);
                }
                thumbnailsContainer.getChildAt(position).setSelected(true);
                listener.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                listener.onPageScrollStateChanged(state);
            }
        });
    }

    private final ViewPager.SimpleOnPageChangeListener viewPagerChangeListener = new ViewPager
            .SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            scroll(thumbnailsContainer.getChildAt(position));
            for (int i = 0; i < thumbnailsContainer.getChildCount(); i++) {
                thumbnailsContainer.getChildAt(i).setSelected(false);
            }
            thumbnailsContainer.getChildAt(position).setSelected(true);
        }
    };

    private void scroll(View thumbnail) {
        int thumbnails[] = new int[2];
        thumbnail.getLocationOnScreen(thumbnails);
        int thumbnailCenterX = thumbnails[0] + thumbnailSize / 2;
        int thumbnailDelta = SmartSeal.screenWidth / 2 - thumbnailCenterX;
        horizontalScrollView.smoothScrollBy(-thumbnailDelta, 0);
    }

    private final OnClickListener thumbnailOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem((int) v.getTag(), true);
        }
    };
}
